/**
 * API工具函数
 * 提供通用的数据处理和格式化功能
 */

import { ERROR_MESSAGES, ERROR_CODES } from './config';

/**
 * 格式化日期时间
 * @param {string|Date} date 日期
 * @param {string} format 格式类型
 * @returns {string} 格式化后的日期
 */
export const formatDateTime = (date, format = 'datetime') => {
  if (!date) return '';
  
  const d = new Date(date);
  if (isNaN(d.getTime())) return '';
  
  const year = d.getFullYear();
  const month = String(d.getMonth() + 1).padStart(2, '0');
  const day = String(d.getDate()).padStart(2, '0');
  const hours = String(d.getHours()).padStart(2, '0');
  const minutes = String(d.getMinutes()).padStart(2, '0');
  const seconds = String(d.getSeconds()).padStart(2, '0');
  
  switch (format) {
    case 'date':
      return `${year}-${month}-${day}`;
    case 'time':
      return `${hours}:${minutes}:${seconds}`;
    case 'datetime':
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    case 'locale':
      return d.toLocaleString('zh-CN');
    default:
      return d.toLocaleString('zh-CN');
  }
};

/**
 * 格式化相对时间
 * @param {string|Date} date 日期
 * @returns {string} 相对时间描述
 */
export const formatRelativeTime = (date) => {
  if (!date) return '';
  
  const now = new Date();
  const target = new Date(date);
  const diff = now - target;
  
  const minute = 60 * 1000;
  const hour = 60 * minute;
  const day = 24 * hour;
  const week = 7 * day;
  const month = 30 * day;
  const year = 365 * day;
  
  if (diff < minute) {
    return '刚刚';
  } else if (diff < hour) {
    return `${Math.floor(diff / minute)}分钟前`;
  } else if (diff < day) {
    return `${Math.floor(diff / hour)}小时前`;
  } else if (diff < week) {
    return `${Math.floor(diff / day)}天前`;
  } else if (diff < month) {
    return `${Math.floor(diff / week)}周前`;
  } else if (diff < year) {
    return `${Math.floor(diff / month)}个月前`;
  } else {
    return `${Math.floor(diff / year)}年前`;
  }
};

/**
 * 生成唯一ID
 * @param {string} prefix 前缀
 * @returns {string} 唯一ID
 */
export const generateId = (prefix = '') => {
  const timestamp = Date.now();
  const random = Math.random().toString(36).substr(2, 9);
  return prefix ? `${prefix}_${timestamp}_${random}` : `${timestamp}_${random}`;
};

/**
 * 深拷贝对象
 * @param {any} obj 要拷贝的对象
 * @returns {any} 拷贝后的对象
 */
export const deepClone = (obj) => {
  if (obj === null || typeof obj !== 'object') return obj;
  if (obj instanceof Date) return new Date(obj.getTime());
  if (obj instanceof Array) return obj.map(item => deepClone(item));
  if (typeof obj === 'object') {
    const clonedObj = {};
    for (const key in obj) {
      if (obj.hasOwnProperty(key)) {
        clonedObj[key] = deepClone(obj[key]);
      }
    }
    return clonedObj;
  }
  return obj;
};

/**
 * 防抖函数
 * @param {Function} func 要防抖的函数
 * @param {number} delay 延迟时间
 * @returns {Function} 防抖后的函数
 */
export const debounce = (func, delay = 300) => {
  let timeoutId;
  return function (...args) {
    clearTimeout(timeoutId);
    timeoutId = setTimeout(() => func.apply(this, args), delay);
  };
};

/**
 * 节流函数
 * @param {Function} func 要节流的函数
 * @param {number} delay 延迟时间
 * @returns {Function} 节流后的函数
 */
export const throttle = (func, delay = 300) => {
  let lastCall = 0;
  return function (...args) {
    const now = Date.now();
    if (now - lastCall >= delay) {
      lastCall = now;
      return func.apply(this, args);
    }
  };
};

/**
 * 数组排序
 * @param {Array} array 要排序的数组
 * @param {string} field 排序字段
 * @param {string} order 排序方向
 * @returns {Array} 排序后的数组
 */
export const sortArray = (array, field = 'createTime', order = 'desc') => {
  if (!Array.isArray(array)) return [];
  
  return array.sort((a, b) => {
    const aVal = a[field];
    const bVal = b[field];
    
    if (aVal === bVal) return 0;
    
    let comparison = 0;
    if (aVal > bVal) {
      comparison = 1;
    } else if (aVal < bVal) {
      comparison = -1;
    }
    
    return order === 'desc' ? -comparison : comparison;
  });
};

/**
 * 数组分页
 * @param {Array} array 要分页的数组
 * @param {number} page 页码
 * @param {number} pageSize 每页大小
 * @returns {Object} 分页结果
 */
export const paginateArray = (array, page = 1, pageSize = 10) => {
  if (!Array.isArray(array)) {
    return {
      data: [],
      total: 0,
      page,
      pageSize,
      totalPages: 0
    };
  }
  
  const total = array.length;
  const totalPages = Math.ceil(total / pageSize);
  const startIndex = (page - 1) * pageSize;
  const endIndex = startIndex + pageSize;
  const data = array.slice(startIndex, endIndex);
  
  return {
    data,
    total,
    page,
    pageSize,
    totalPages
  };
};

/**
 * 搜索过滤
 * @param {Array} array 要搜索的数组
 * @param {string} keyword 搜索关键词
 * @param {Array} fields 搜索字段
 * @returns {Array} 搜索结果
 */
export const searchArray = (array, keyword, fields = []) => {
  if (!Array.isArray(array) || !keyword) return array;
  
  const lowerKeyword = keyword.toLowerCase();
  
  return array.filter(item => {
    if (fields.length === 0) {
      // 搜索所有字符串字段
      return Object.values(item).some(value => {
        if (typeof value === 'string') {
          return value.toLowerCase().includes(lowerKeyword);
        }
        return false;
      });
    } else {
      // 搜索指定字段
      return fields.some(field => {
        const value = item[field];
        if (typeof value === 'string') {
          return value.toLowerCase().includes(lowerKeyword);
        }
        return false;
      });
    }
  });
};

/**
 * 错误处理
 * @param {Error} error 错误对象
 * @returns {Object} 格式化的错误信息
 */
export const handleError = (error) => {
  console.error('API Error:', error);
  
  let message = ERROR_MESSAGES.UNKNOWN_ERROR;
  let code = ERROR_CODES.INTERNAL_ERROR;
  
  if (error.message) {
    message = error.message;
  }
  
  if (error.code) {
    code = error.code;
  }
  
  return {
    code,
    message,
    timestamp: new Date().toISOString()
  };
};

/**
 * 成功响应格式化
 * @param {any} data 响应数据
 * @param {string} message 成功消息
 * @returns {Object} 格式化的成功响应
 */
export const formatSuccessResponse = (data, message = '操作成功') => {
  return {
    code: ERROR_CODES.SUCCESS,
    message,
    data,
    timestamp: new Date().toISOString()
  };
};

/**
 * 验证必填字段
 * @param {Object} data 要验证的数据
 * @param {Array} requiredFields 必填字段列表
 * @returns {Object} 验证结果
 */
export const validateRequiredFields = (data, requiredFields) => {
  const missingFields = [];
  
  requiredFields.forEach(field => {
    if (!data[field] || (typeof data[field] === 'string' && data[field].trim() === '')) {
      missingFields.push(field);
    }
  });
  
  return {
    isValid: missingFields.length === 0,
    missingFields
  };
};

/**
 * 生成分页参数
 * @param {Object} params 查询参数
 * @returns {Object} 分页参数
 */
export const generatePaginationParams = (params = {}) => {
  const {
    page = 1,
    pageSize = 10,
    sortField = 'createTime',
    sortOrder = 'desc',
    keyword = ''
  } = params;
  
  return {
    page: Math.max(1, parseInt(page)),
    pageSize: Math.min(100, Math.max(1, parseInt(pageSize))),
    sortField,
    sortOrder: ['asc', 'desc'].includes(sortOrder) ? sortOrder : 'desc',
    keyword: keyword.trim()
  };
};
